<template>
  <div
    class="yydj-header flex items-center w-full h-40px px-22px justify-between"
    style="flex-shrink: 0"
  >
    <Breadcrumb v-if="!$slots.leftExtra" />
    <slot v-else name="leftExtra"></slot>
    <div class="flex items-center">
      <div v-if="props.showSearch" class="mr-32px h-28px w-212px flex items-center relative">
        <n-input
          v-model:value="searchContent"
          type="text"
          placeholder="搜索"
          clearable
          style="height: 28px"
          @input="handleSearchChange"
          @blur="handleBlur"
        >
          <template #prefix>
            <img :src="search" alt="" />
          </template>
        </n-input>
        <transition name="zoom">
          <div
            v-if="spus.length"
            ref="searchResultAction"
            class="w-212px absolute z-10 top-30px bg-white rounded-4px max-h-128px overflow-y-auto"
          >
            <div
              v-for="(spu, index) in spus"
              :key="spu.id"
              class="h-32px w-212px px-12px text-14px text-black leading-32px cursor-pointer search-content"
              :class="{ active: index === activeIndex }"
              @click="godetail(spu)"
            >
              {{ spu.name.replace(searchContent, '')
              }}<span class="color-main">{{ searchContent }}</span>
            </div>
          </div>
        </transition>
      </div>
      <div class="w-20px h-20px mr-6px"><img :src="computer" alt="" /></div>
      <div class="text-14px text-white mr-32px">{{ contextStore.no }}</div>
      <div class="w-20px h-20px mr-32px cursor-pointer relative" @click="gocart">
        <img :src="cart" alt="" />
        <div
          class="absolute bg-badge w-18px h-18px leading-18px text-center rounded-[50%] text-12px text-white -top-8px -right-10px cart-header-icon"
        >
          {{ cartStore.totalPieces }}
        </div>
      </div>
      <div v-if="!name" class="w-20px h-20px mr-6px"><img :src="login" /></div>
      <div
        v-if="!name"
        class="text-14px text-white opacity-60 font-medium cursor-pointer"
        @click="() => user.invokeLogin(true)"
      >
        登陆
      </div>
      <div v-else class="flex items-center" @mouseleave="showExit = false">
        <div class="w-20px h-20px cursor-pointer flex" @mouseenter="showExit = true">
          <n-dropdown trigger="click" :options="options" @select="handleSelect">
            <n-avatar round :size="20" :src="user.GetAvatar" />
          </n-dropdown>
        </div>
      </div>
    </div>
  </div>
  <!-- <transition name="bounce"> -->
  <Login v-if="user.GetPending" @on-close="closeLogin" />
  <!-- </transition> -->
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import computer from '@renderer/assets/computer.svg'
import cart from '@renderer/assets/cart.svg'
import login from '@renderer/assets/login.svg'
import search from '@renderer/assets/search.svg'
import Breadcrumb from '@renderer/components/breadcrumb/index.vue'
import { useUserStore } from '@renderer/store/modules/user'
import Login from './login.vue'
import { useCartStore } from '@renderer/store/modules/cart'
import { useContextStore } from '@renderer/store/modules/context'
import useHttp from '@renderer/utils/http'
import { NDropdown } from 'naive-ui'
const user = useUserStore()
const router = useRouter()
const cartStore = useCartStore()
const contextStore = useContextStore()
const showExit = ref<boolean>(false)
const spus = ref<any[]>([])
const searchContent = ref<any>(null)
const activeIndex = ref<number | null>(null)
const searchResultAction = ref<HTMLElement | null>(null)
const name = computed(() => {
  return user.GetUserName
})
const options = ref<any>([
  {
    key: 'center',
    label: '个人中心'
  },
  {
    key: 'out',
    label: '退出'
  }
])

const handleSelect = (v) => {
  if (v === 'center') {
    goCenter()
  } else if (v === 'out') {
    user.loginout()
    cartStore.clear('local')
    router.replace({ name: 'Mall' })
  }
}
const props = defineProps({
  showSearch: {
    type: Boolean,
    default: true
  }
})
const closeLogin = () => {
  user.invokeLogin(false)
}

const goCenter = () => {
  router.replace('/user/index')
}

const gocart = () => {
  router.replace({ name: 'Cart' })
}
// 搜索
const handleSearchChange = async (v) => {
  const { data: res } = await useHttp(`/product/c/search?content=${v}`).get().json()
  if (res.value.code === 200) {
    spus.value = res.value.data
  }
}
// 搜索结果
const godetail = (spu) => {
  router.replace({ name: 'Detail', params: { id: spu.id } })
  searchContent.value = spu.name
  spus.value = []
  activeIndex.value = null
}
// 失去焦点
const handleBlur = () => {
  spus.value = []
  searchContent.value = null
}

const goout = () => {
  user.loginout()
}
onMounted(() => {
  if (user.GetToken) {
    cartStore.init()
  }
  window.addEventListener('keydown', (e) => {
    if (spus.value.length) {
      const code = e.which || e.keyCode
      if (code === 40) {
        if (activeIndex.value === null) {
          activeIndex.value = 0
        } else if (activeIndex.value !== spus.value.length - 1) {
          activeIndex.value = activeIndex.value + 1
        }
        if (activeIndex.value > 3) {
          searchResultAction.value?.scrollTo(0, (activeIndex.value - 3) * 32)
        }
      } else if (code === 38) {
        if (activeIndex.value === null) {
          activeIndex.value = spus.value.length - 1
        } else if (activeIndex.value !== 0) {
          activeIndex.value = activeIndex.value - 1
        }
        if (activeIndex.value > 3) {
          searchResultAction.value?.scrollTo(0, (activeIndex.value - 3) * 32)
        } else {
          searchResultAction.value?.scrollTo(0, 0)
        }
      } else if (code === 13) {
        if (activeIndex.value !== null) {
          const spu = spus.value[activeIndex.value]
          if (spu) {
            searchContent.value = spu.name
            router.replace({ name: 'Detail', params: { id: spu.id } })
            spus.value = []
            activeIndex.value = null
          }
        }
      }
    }
  })
})
</script>

<style scoped>
.yydj-header {
  background-color: rgba(0, 0, 0, 0.7);
}
.yydj-header ::v-deep(.n-input) {
  background: rgba(255, 255, 255, 0.16);
  border-radius: 4px;
  box-sizing: border-box;
}
.yydj-header ::v-deep(.n-input__input) {
  --n-caret-color: #fff;
  --n-text-color: #fff;
  --n-placeholder-color: rgba(255, 255, 255, 0.6);
}
.yydj-header ::v-deep(.n-input__border) {
  --n-border: none;
}
.yydj-header ::v-deep(.n-input__state-border) {
  --n-border-hover: 1px solid #4979ff;
  --n-border-focus: 1px solid #4979ff;
}
.yydj-header ::v-deep(.n-input__input-el) {
  height: 28px;
}
.search-content:hover {
  background-color: #edf2ff;
}
.yydj-header .active {
  background-color: #edf2ff;
}
</style>
